$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_gjxlkz_m")
    const dgrid1 = $NG.getCmpApi("p_form_gjxlkz_d1")
    const getHeadValue = (str) => mstform.getItem(str).getValue()
    let timeId = 0
    let timeId1 = 0


    if (page.oType == 'add') {
        mstform.getItem("u_nd").setValue({
            label: new Date().getFullYear(),
            value: new Date().getFullYear()
        })
    }
    useClick(()=>{
        getFileId()
    },"u_xzdrmb")
    // 计数器
    function a() {
        let i = 0
        return function () {
            return i++
        }
    }
    const reduceNum = a()
    // 进度锁，不变化就不锁防止持续设置导致性能额外输出
    let num = 0
    let lock = false
    // 启动
    setInterval(() => {
        setDom()
    }, 0)
    dgrid1.getRef().bodyRef.current.addEventListener("wheel", function (e) {
        if (timeId) {
            clearTimeout(timeId)
        }
        timeId = setTimeout(() => {
            lock = false
        }, 10)
        console.log("滚动方向：", e.deltaY > 0 ? "向下" : "向上", "数值：", e.deltaY);
    });
    dgrid1.getRef().bodyRef.current.childNodes[0].addEventListener("scroll", function (e) {
        if (timeId) {
            clearTimeout(timeId)
        }
        timeId = setTimeout(() => {
            lock = false
        }, 10)
    });
    useUpdateRows(({ args }) => {
        // 启动进的设置
        const rows = args[0]
        rows.forEach(el => {
            if (!el.u_gcl) {
                $NG.message("请先填写工程量！")
            }
            el.u_xxjd = ((Number((Number(el.u_sjwcl) || 0) / (Number(el.u_gcl) || 0)) || 0) * 100) + "-" + (100 - ((Number((Number(el.u_sjwcl) || 0) / (Number(el.u_gcl) || 0)) || 0) * 100))
            el.u_jhljwcgcl = (Number(el.u_jhwcl) || 0)
            el.u_sjljwcgcl = (Number(el.u_sjwcl) || 0)
            el.u_jhljwcbfb = (Number((Number(el.u_jhljwcgcl) || 0) / (Number(el.u_gcl) || 0)) || 0)
            el.u_sjljwcbfb = (Number((Number(el.u_sjljwcgcl) || 0) / (Number(el.u_gcl) || 0)) || 0)
            el.u_zhbl = ((Number(el.u_jhljwcbfb) || 0) - (Number(el.u_sjljwcbfb) || 0)).toFixed(4)
        })
        if (timeId1) {
            clearTimeout(timeId1)
        }
        timeId1 = setTimeout(() => {
            lock = false
        }, 1200)
        dgrid1.refreshView()
    }, "p_form_gjxlkz_d1")

    useUpdateRow(({ args }) => {
        // 启动进的设置
        const rows = args[0]
        rows.forEach(el => {

            el.u_xxjd = ((Number((Number(el.u_sjwcl) || 0) / (Number(el.u_gcl) || 0)) || 0) * 100) + "-" + (100 - ((Number((Number(el.u_sjwcl) || 0) / (Number(el.u_gcl) || 0)) || 0) * 100))
            el.u_jhljwcgcl = (Number(el.u_jhwcl) || 0)
            el.u_sjljwcgcl = (Number(el.u_sjwcl) || 0)
            el.u_jhljwcbfb = (Number((Number(el.u_jhljwcgcl) || 0) / (Number(el.u_gcl) || 0)) || 0)
            el.u_sjljwcbfb = (Number((Number(el.u_sjljwcgcl) || 0) / (Number(el.u_gcl) || 0)) || 0)
            el.u_zhbl = ((Number(el.u_jhljwcbfb) || 0) - (Number(el.u_sjljwcbfb) || 0)).toFixed(4)
        })
        if (timeId1) {
            clearTimeout(timeId1)
        }
        timeId1 = setTimeout(() => {
            lock = false
        }, 1200)
        dgrid1.refreshView()
    }, "p_form_gjxlkz_d1")


    // 获取金额汇总
    function amtTotal() { }

    // dom处理
    window._lsz = setDom
    function setDom() {
        if (lock) return
        console.log(`开始`,);
        try {
            if (!window._catch_style) {
                // %创建一个style 缓存到全局
                window._catch_style = document.createElement('style')
                document.head.appendChild(window._catch_style);
            }

            // %设置每个字段的css把他缓存到这个对象
            window._catch_style_map = {}
            const ref = dgrid1.getRef().bodyRef.current
            // %获取底层表格table
            const table = ref.childNodes[0].childNodes[0]
            // %临时存储要改进度的dom
            let jdDom = null

            const rows = dgrid1.getRows()
            // %循环每一行
            table.childNodes.forEach((rowDom, ind) => {
                let sj = rows[ind].u_sjwcl
                let js = rows[ind].u_jhwcl
                let color = "#fff"
                if ((Number(rows[ind].u_zhbl) || 0) >= 0.2) {
                    color = "#ff8800ff"
                }

                const elDoms = rowDom.childNodes
                // %循环每一行的每一列
                elDoms.forEach(el => {
                    // %获取id
                    let id = el.id
                    const key = el.getAttribute("data-key")
                    el.style.background = color
                    if (key == 'u_xxjd') {
                        if (!rows[ind].u_gcl) return
                        if (!id) {
                            el.id = `a${new Date().getTime()}${reduceNum()}-fack`
                            id = `a${new Date().getTime()}${reduceNum()}-fack`
                        }
                        // %查找要改成进度的哪一行
                        const content = rows[ind].u_xxjd

                        // %配置进度
                        if (content.includes("-")) {
                            const val = content.split('-')
                            console.log(`value`, val, val[0]);
                            if (val[0] == undefined || val[1] == undefined) {
                                throw '进度值设置异常！'
                            }
                            // %调整css
                            console.log(`val`, val[0]);
                            const code = `#${id}{position:relative;}#${id}::before{position:absolute;content:"${Math.floor((Number(val[0]) || 0))}%";display:block;top:15%;left:2%;width:${(val[0] / 100) * 96 > 96 ? 96 : (val[0] / 100) * 96}%;height:70%;color:#fff!important;text-align:center;z-index:99999;background:#10f500;}#${id}::after{position:absolute;content:"${Math.floor((Number(val[1]) || 0))}%";display:block;top:15%;right:2%;width:${(val[1] / 100) * 96 > 96 ? 96 : (val[1] / 100) * 96}%;height:70%;color:#fff;text-align:center;z-index:99999;background:red;}`
                            window._catch_style_map[id] = code
                        }
                    } else {

                    }

                })
            })
            // %设置style
            let styleCss = ''
            for (let k in window._catch_style_map) {
                styleCss += ` ${window._catch_style_map[k]} `
            }
            window._catch_style.innerHTML = styleCss
            console.log(`style`, styleCss);
        } catch (err) {
            console.log(`设置进度报错`, err);
        }
        num++
        // 启动2次防止 空大
        if (num > 2) {
            lock = true
            num = 0
        }
    }


    // 查询附件，找到附件的数量
    async function getFileId() {
        let asr = null
        await $NG.execServer("getAttachmentByasr", { code: '5e32d2d1-bdc6-4a6f-8a67-6e4813f58673' }, (res) => {
            if (res.count == 0) {
                asr = null
            } else {
                asr = JSON.parse(res.data)[0].extendObjects
            }
        })
        if (!asr) {
            $NG.alert("没有模板可以下载！")
            return
        }
        const origin = location.origin;
        const router = "/JFileSrv/reactAttach/download";
        const param = {
            asrFid: asr.asr_fid,
            asrName: asr.asr_name,
            busTypeCode: "drmb",
            loginId: "6870000000000016",
            orgId: "1",
            asrFilldt: asr.asr_filldt
        };

        const query = new URLSearchParams(param).toString();
        const url = `${origin}${router}?${query}`;

        try {
            // 1. fetch 请求，加上你需要的 header
            const res = await fetch(url, {
                method: "GET",
                headers: {
                    "Authorization": localStorage.getItem("Auth$#$i8$#$6.3sp1$#$lsz"),
                    "dbtoken": "0001", // 🔴 在这里加请求
                }
            });

            if (!res.ok) {
                throw new Error("下载失败: " + res.status);
            }
            // 从响应头解析文件名
            const disposition = res.headers.get("Content-Disposition");
            let filename = asr.asr_name
            if (disposition && disposition.includes("filename=")) {
                const match = disposition.match(/filename="?([^"]+)"?/);
                if (match.length > 1) {
                    filename = decodeURIComponent(match[1]);
                }
            }
            // 转 blob
            const blob = await res.blob();

            // 创建临时链接并下载
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = filename; // ✅ 指定文件名
            link.target = "_blank";
            document.body.appendChild(link);
            link.click();
            link.remove();

            setTimeout(() => URL.revokeObjectURL(link.href), 60000);
        } catch (err) {
            console.error(err);
            $NG.alert("下载出错啦！");
        }
        // const button = document.createElement('a');
        // button.style.display = 'none'
        // button.href = url
        // document.body.appendChild(button);
        // button.click()

    }
})